<template>
<!--填写预约信息弹窗 s-->
<view class="pop-prkage-wraps" id="bespeak" style="position: fixed;width: 100%;height: 100%; z-index: 6;top: 0;left: 0; overflow:scroll">
    <!-- <view class="z-Package-hrader">
        <view class="z-Package-icon Package-icon-close" id="bespeak_close"><image src='../../../images/withdraw-left.png'></image></view>
        填写预约信息
    </view> -->

    <form id="bespeak_form">
        <view class="bookinfo_con">
            <view v-for="(template_unit, index) in bespeak_template_unit" :key="index">
            <!-- 单文本输入框 -->
                    <view v-if="template_unit['type'] == 1">
                        <view class="bookinfo_list bookinfo_list_a">
                          <label>{{template_unit['title']}}<text class="i">{{template_unit['required']==1?"*":""}}</text></label>
                            <input :type="template_unit['format'] == 'mobile' ? 'number' : 'text'" @input="verInput" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :placeholder="template_unit['placeholder']" :value="input_val[template_unit['template_unit_id']]" :data-input_id="template_unit['template_unit_id']"></input>
                        </view>
                    </view>
            <!-- 多文本输入框 -->
                    <view v-if="template_unit['type'] == 2">
                        <view class="bookinfo_list bookinfo_mesg">
                            <label>{{template_unit['title']}}:<text style="color: #ff6a00">{{template_unit['required']==1?"*":""}}</text></label>
                            <textarea maxlength="255" :value="input_val[template_unit['template_unit_id']]" type="textarea" @input="verInput" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :data-title="template_unit['title']" :placeholder="template_unit['placeholder']" :data-input_id="template_unit['template_unit_id']" auto-height></textarea>
                            
                        </view>
                    </view>

                    <!-- 单选 -->
                    <view v-if="template_unit['type'] == 3">
                        <view class="bookinfo_list bookinfo_radios">
                            <label>{{template_unit['title']}}：<text class="i">{{template_unit['required']==1?"*":""}}</text></label>
                            
                            <radio-group class="radio-group" @change="verInput" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :data-verify="(template_unit['required']?'required':'') + '' + (template_unit['format']?'|':'') + '' + (template_unit['format']?template_unit[format]:'')">
                            <label v-for="(item, index2) in template_unit['value_arr']" :key="index2" class="radio">
                                <radio :value="item" :checked="item.checked"></radio>{{item}}
                            </label>
                            </radio-group>
                        </view>
                    </view>

                    <!-- 多选 -->
                    <view v-if="template_unit['type'] == 4">
                        <view class="bookinfo_list bookinfo_checkbox">
                            <label>{{template_unit['title']}}：<text class="i">{{template_unit['required']==1?"*":""}}</text></label>
                            <!-- 渲染已填写的值的checkbox -->
                            <checkbox-group v-if="checkbox_val[template_unit['template_unit_id']]" @change="checkBoxChange" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :data-check_id="template_unit['template_unit_id']" :data-index="index">
                                <checkbox v-for="(item, index2) in checkbox_val[template_unit['template_unit_id']]" :key="index2" :value="item.value" :checked="item.checked">{{item.name}}</checkbox>
                            </checkbox-group>
                            <!-- 渲染未填写的值checkbox -->
                            <checkbox-group v-else @change="checkBoxChange" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :data-check_id="template_unit['template_unit_id']" :data-index="index"> 
                                <checkbox v-for="(item, index2) in template_unit['value_arr']" :key="index2" :value="item">{{item}}</checkbox>
                            </checkbox-group>

                        </view>
                    </view>

                    <!-- 下拉框 -->
                    <view v-if="template_unit['type'] == 5">
                        <view class="bookinfo_list bookinfo_list_select">
                            <label>{{template_unit['title']}}：<text class="i">{{template_unit['required']==1?"*":""}}</text></label>

                            <picker @change="bindPickerChange" :data-value_arr="template_unit['value_arr']" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :range="template_unit['value_arr']" :data-picker_id="template_unit['template_unit_id']">
                              <view class="picker" v-if="picker_val[template_unit['template_unit_id']]">
                                {{picker_val[template_unit['template_unit_id']]}}
                                </view>
                              <view class="picker" v-else>
                                请选择
                              </view>
                            </picker>

                            
                            <i class="bookinfo_list_left"></i>
                        </view>
                    </view>
                    <!-- 上传单图 -->
                    <view v-if="template_unit['type'] == 6">   
                        <view class="bookinfo_list bookinfo_mesg">
                            <label class="bookinfo_tp_name">{{template_unit['title']}}：<text class="i">{{template_unit['required']==1?"*":""}}</text></label>
                            <view class="bookinfo_tp " @tap="uploadImg" data-limit="1" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :data-img_id="template_unit['template_unit_id']">上传图片 </view>
                            <view class="bookinfo_list_Ulimg " style="width: auto;min-width: 1.6rem;margin:.3rem 0;">
                                  <view v-for="(item, index2) in img_url[template_unit['template_unit_id']]" :key="index2" class="li">
                                      <image :src="url + '' + item"></image>
                                      <view class="span" @tap="delImg" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :data-img_id="template_unit['template_unit_id']" :data-index="index">×</view>
                                  </view>
                                    
                            </view>
                        </view>
                    </view>
                   <view v-if="template_unit['type'] == 7">
                        <!--多张图片-->
                       <view class="bookinfo_list bookinfo_mesg">
                            <label class="bookinfo_tp_name">{{template_unit['title']}}：<text class="i">{{template_unit['required']==1?"*":""}}</text></label>
                            <view class="bookinfo_tp " @tap="uploadImg" data-limit="4" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :data-img_id="template_unit['template_unit_id']">上传图片 </view>
                            <view class="bookinfo_list_Ulimg ul_li" style="width: auto;min-width: 1.6rem;margin:.3rem 0;">
                                  <view v-for="(item, index2) in img_url[template_unit['template_unit_id']]" :key="index2" class="img-item" style="width:150rpx; height:150rpx; position: relative">
                                      <image :src="url + '' + item"></image>
                                      <view class="span" @tap="delImg" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'" :data-img_id="template_unit['template_unit_id']" :data-index="index">×</view>
                                  </view>
                            </view>
                        </view>
                    </view>
                    <view v-if="template_unit['type'] == 8">
                        <view class="bookinfo_list bookinfo_mesg">
                            <label class="bookinfo_tp_name">{{template_unit['title']}}：<text class="i">{{template_unit['required']==1?"*":""}}</text></label>     
                            <view></view>
                            <view class="time-picker-str" @tap="openTimePicker" :data-name="'bespeak_form[' + template_unit['template_unit_id'] + ']'">选择时间  {{time_str}}</view>
                        </view>
                    </view>
            </view>


            <view class="time-picker-mask" @tap="closeTimePicker" :hidden="!time_picker"></view>
            <view class="time-picker" :hidden="!time_picker">
                <view class="time-picker-header">
                  <view class="btn-cancel" @tap="closeTimePicker">取消</view>
                  <view>选择日期</view>
                  <view class="btn-success" @tap="bindTimePickerData">确认</view>
                </view>
                <view class="time-picker-body">
                    <picker-view indicator-style="height: 50px;" :value="picker_view_value" @change="TimePickerChange" style="width: 100%; height: 300rpx;">
                      <picker-view-column>
                        <view v-for="(item, index) in years" :key="index" style="line-height: 50px">{{item}}年</view>
                      </picker-view-column>
                      <picker-view-column>
                        <view v-for="(item, index) in months" :key="index" style="line-height: 50px">{{item}}月</view>
                      </picker-view-column>
                      <picker-view-column>
                        <view v-for="(item, index) in days" :key="index" style="line-height: 50px">{{item}}日</view>
                      </picker-view-column>
                      <picker-view-column>
                        <view v-for="(item, index) in hours" :key="index" style="line-height: 50px">{{item}}时</view>
                      </picker-view-column>
                    </picker-view>
                </view>
            </view>

            <view class="Package-footer-btn" style="margin-top: 1.344rem;">
                <button @tap="verifyFormData">确定</button>
            </view>
        </view>
    </form>
</view>
<!--填写预约信息弹窗 e-->
</template>

<script>
// pages/test/test.js
var app = getApp();
var request = app.globalData.request;
var util = require("../../../../utils/util.js");
const date = new Date();
const years = [date.getFullYear()];
const months = [];
const days = [];
const hours = []; // for (let i = 2018; i <= date.getFullYear(); i++) {
//   years.push(i)
// }

export default {
  data() {
    return {
      form_data: {},
      picker_val: {},
      time_picker: false,
      years: years,
      months: months,
      days: days,
      hours: hours,
      time_str: '',
      img_url: {},
      url: app.globalData.setting.url,
      bespeak_template_unit: {},
      picker_view_value: [0, date.getMonth(), date.getDate() - 1, date.getHours()],
      time_start: "",
      time_end: "",
      form_type: "",
      input_val: "",
      checkbox_val: "",
      picker_time_val: ""
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    uni.getStorage({
      key: 'bespeakFormData',
      success: function (res) {
        that.setData(res.data);
      }
    });
    uni.getStorage({
      key: 'bespeak_template_unit',
      success: function (res) {
        that.formVerifyType(res.data);
        that.setData({
          time_start: util.format(new Date().getTime() / 1000, 'yyyy-MM-dd'),
          time_end: util.format(new Date().getTime() / 1000 + 31536000, 'yyyy-MM-dd'),
          bespeak_template_unit: res.data
        });
      }
    });
  },
  methods: {
    verifyFormData: function () {
      //遍历form_data
      var that = this;
      var form_type = this.form_type;
      var status = true;

      for (var k in form_type) {
        if (!that.verifyFunc(k)) {
          status = false;
          break;
        }
      }

      if (status) {
        uni.setStorage({
          key: 'bespeakFormData',
          data: this,
          success: function (res) {
            uni.navigateBack({
              delta: 1
            });
          }
        });
      }
    },
    verifyFunc: function (type_name) {
      var status = true;
      var value = this.form_data[type_name];

      if (typeof value == 'object') {
        value = value[0];
      }

      var _type = this.form_type[type_name].format;
      var _required = this.form_type[type_name].required;
      var title = this.form_type[type_name].title;
      var name = this.form_type[type_name].name;

      if (1 == _required && (value == '' || value == undefined)) {
        uni.showModal({
          title: '操作提示',
          content: title + '为必填项',
          showCancel: false
        });
        return false;
      }

      if (name == 'user_name') {
        this.setData({
          "form_data.consignee": value
        });
      } //加入take_time字段


      if (name == 'take_time') {
        this.setData({
          "form_data.take_time": new Date(value.replace('-', '/').replace('-', '/').replace(' ', '  ')).getTime() / 1000
        });
      } //加入mobile字段


      if (name == 'user_mobile') {
        this.setData({
          "form_data.mobile": value
        });
      }

      if (value) {
        switch (_type) {
          case 'mobile':
            if (!/^1[34578]\d{9}$/.test(value)) {
              status = false;
            }

            break;

          case 'phone':
            if (!/^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/.test(value)) {
              status = false;
            }

            break;

          case 'identity':
            if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
              status = false;
            }

            break;

          case 'zip_code':
            if (!/^[0-9][0-9]{5}$/.test(value)) {
              status = false;
            }

            break;

          case 'email':
            if (!/[a-z0-9A-Z_-]+@[a-z0-9A-Z_-]+(\.[a-z]{2,5}){1,2}/.test(value)) {
              status = false;
            }

            break;

          case 'url':
            if (!/[a-zA-z]+:\/\/[^\s]*/.test(value)) {
              status = false;
            }

            break;
        }
      }

      if (!status) {
        uni.showModal({
          title: '操作提示',
          content: title + '格式不对',
          showCancel: false
        });
      }

      return status;
    },
    formVerifyType: function (data) {
      var form_type = {};
      data.forEach(function (o) {
        form_type['bespeak_form[' + o.template_unit_id + ']'] = {
          required: o.required,
          format: o.format,
          title: o.title,
          name: o.name
        };
      });
      this.setData({
        form_type: form_type
      });
    },
    verInput: function (e) {
      var name = e.currentTarget.dataset.name;
      var form_data = this.form_data;
      form_data[name] = e.detail.value;
      var input_val = this.input_val || {};
      input_val[e.currentTarget.dataset.input_id] = e.detail.value;
      this.setData({
        form_data: form_data,
        input_val: input_val
      });
    },
    checkBoxChange: function (e) {
      var _val = e.detail.value;
      var _index = e.currentTarget.dataset.index;
      var _check_item = this.bespeak_template_unit[_index].value_arr;
      var _check_group = [];

      for (var i in _check_item) {
        _check_group.push({
          name: _check_item[i],
          value: _check_item[i],
          checked: false
        });
      }

      for (var k in _val) {
        for (var j in _check_group) {
          if (_val[k] == _check_group[j].value) {
            _check_group[j].checked = true;
          }
        }
      }

      var name = e.currentTarget.dataset.name;
      var form_data = this.form_data;
      var checkbox_val = this.checkbox_val || {};
      checkbox_val[e.currentTarget.dataset.check_id] = _check_group;
      form_data[name] = _val;
      this.setData({
        form_data: form_data,
        checkbox_val: checkbox_val
      });
    },
    checkboxCtype: function (e) {
      value.forEach(function (o, i) {
        var _name = name + '[' + i + ']';

        form_data[_name] = o;
      });
      this.setData({
        form_data: form_data
      });
    },
    bindPickerChange: function (e) {
      var name = e.currentTarget.dataset.name;
      var form_data = this.form_data;
      var value_arr = e.currentTarget.dataset.value_arr;
      var picker_id = e.currentTarget.dataset.picker_id;
      form_data[name] = value_arr[e.detail.value];
      var picker_val = this.picker_val;
      picker_val[picker_id] = value_arr[e.detail.value];
      this.setData({
        picker_val: picker_val,
        form_data: form_data
      });
    },
    bindDateChange: function (e) {
      var name = e.currentTarget.dataset.name;
      var form_data = this.form_data;
      var picker_id = e.currentTarget.dataset.picker_id;
      var picker_time_val = this.picker_time_val;
      picker_time_val[picker_id] = e.detail.value;
      this.setData({
        picker_time_val: picker_time_val,
        form_data: form_data
      });
    },
    closeTimePicker: function () {
      this.setData({
        time_picker: false
      });
    },
    openTimePicker: function (e) {
      //判断是否已选择时间
      this.setData({
        time_picker: e.currentTarget.dataset.name
      });
    },
    bindTimePickerData: function () {
      var time_str = this.time_str.replace('-', '/').replace(' ', '  ');
      var timestamp = new Date(time_str).getTime();

      if (timestamp < date.getTime()) {
        uni.showModal({
          title: '操作提示',
          content: '选择的时间应大于当前时间',
          showCancel: false
        });
        return false;
      } //存入form_data中


      var form_data = this.form_data;
      form_data[this.time_picker] = this.time_str;
      this.setData({
        form_data: form_data
      });
      this.closeTimePicker();
    },
    TimePickerChange: function (e) {
      var value = e.detail.value;
      var y = this.years[value[0]];
      var m = this.months[value[1]];
      var d = this.days[value[2]];
      var h = this.hours[value[3]];
      var time_str = [y, m, d].map(function (n) {
        n = n.toString();
        return n[1] ? n : '0' + n;
      }).join('-') + ' ' + [h, 0, 0].map(function (n) {
        n = n.toString();
        return n[1] ? n : '0' + n;
      }).join(':');
      this.setData({
        time_str: time_str,
        picker_view_value: e.detail.value
      });
    },
    uploadImg: function (e) {
      var that = this;
      uni.chooseImage({
        count: parseInt(e.currentTarget.dataset.limit),
        success: function (res) {
          //判断单、多图上传
          var img_url = that.img_url;

          if (img_url[e.currentTarget.dataset.img_id] && img_url[e.currentTarget.dataset.img_id].length + res.tempFilePaths.length > e.currentTarget.dataset.limit) {
            uni.showModal({
              title: '上传提示',
              content: '最多上传' + e.currentTarget.dataset.limit + '张图片',
              showCancel: false
            });
            return;
          }

          res.tempFilePaths.forEach(function (path) {
            that.doUploadImg(path, e);
          });
        }
      });
    },
    doUploadImg: function (filePath, e) {
      var that = this;
      var options = {
        filePath: filePath,
        name: 'bespeak_img_file',
        success: function (res) {
          var img_url = that.img_url;
          var arr = img_url[e.currentTarget.dataset.img_id] || [];
          arr.push(res.data.data);
          img_url[e.currentTarget.dataset.img_id] = arr;
          var form_data = that.form_data;
          form_data[e.currentTarget.dataset.name] = arr;
          that.setData({
            img_url: img_url,
            form_data: form_data
          });
        }
      };
      request.uploadFile('/api/cart/bespeakUpImg', options);
    },
    delImg: function (e) {
      var img_url = this.img_url;
      var arr = img_url[e.currentTarget.dataset.img_id] || [];
      arr.splice(e.currentTarget.dataset.index, 1);
      img_url[e.currentTarget.dataset.img_id] = arr;
      var form_data = this.form_data;
      form_data[e.currentTarget.dataset.name] = arr;
      this.setData({
        img_url: img_url,
        form_data: form_data
      });
    }
  }
};
</script>
<style>
.pop-prkage-wraps{
  background: #fff
}


.z-Package-hrader {
    height: 100rpx;
    width: 100%;
    position: relative;
    text-align: center;
    font-size: 16pt;
    font-weight: bold;
    border-bottom: 1px solid #f3f3f3;
}

.bookinfo_list, .book_info, .book_store {
    height: auto;
    padding: 0 20rpx;
    border-bottom: 1px solid #f3f3f3;
    font-size: 0.64rem;
    color: #333;
    vertical-align: middle
}

.bookinfo_list_a label {
    max-width: 7.3rem;
    height: 100rpx;
    overflow: hidden;
    display: inline-block;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 100rpx;
    
}



.bookinfo_list_a input {
    float: right;
    width: 300rpx;
    height: 100rpx;
    margin-right: 0.65rem;
    line-height: 100rpx;
    text-align: right;
    font-size: 30rpx;
    
}

.bookinfo_radios radio {
    margin: 10rpx 0;
}

.bookinfo_list_select label,.bookinfo_radios label,.bookinfo_mesg label,.bookinfo_checkbox label{
    display: block;
    margin-top: 30rpx;
}

label {
  font-size: 30rpx;
}

.bookinfo_mesg textarea {
    margin:20rpx 20rpx;
    width: auto;
    border: 1px solid #f3f3f3;
    padding: 20rpx 20rpx;
    font-size: 30rpx;
    color: #333;
    line-height: 30rpx;
}

.bookinfo_list picker {
    width: auto;
    height: 60rpx;
    color: #999;
    font-size: 30rpx;
    margin-top: 30rpx;
}

.Package-footer-btn button {
    width: 100%;
    height: 100rpx;
    border: 0px;
    background-color: #ff6a00;
    color: #fff;
    text-align: center;
    font-size: 40rpx;
    font-weight: 400;
}

.i {
  color: #ff6a00
}

.bookinfo_list .bookinfo_tp {
    float: right;
    height: 50rpx;
    line-height: 50rpx;
    padding: 0 10rpx;
    background: none;
    background-color: #ff6a00;
    margin-left: .3rem;
    text-align: center;
    color: #FFF;
    margin-top: -50rpx;
}

.bookinfo_checkbox checkbox {
     margin: 20rpx 20rpx;
}

.picker {
  margin-top: -20rpx;
}

.time-picker {
  width: 100%;
  height: auto;
  display: block;
  z-index: 999;
  position: fixed;
  bottom: 0;
  background-color: #fff;
}

.time-picker-mask {
  width: 100%;
  height: 200%;
  background-color: #000;
  z-index: 88;
  position: absolute;
  top: 0;
  opacity: 0.5
}

.time-picker-header{
  height: 100rpx;
  font-size: 14pt;
  background-color: #ff6a00;
  color: #FFF;
  text-align: center;
  line-height: 100rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-between
}

.btn-cancel{
  font-size: 10pt;
  margin-left: 20rpx;
}

.btn-success{
  font-size: 10pt;
  margin-right: 20rpx;
}

.time-picker-body{
  margin-top: 0px;
}

.time-picker-str{
  margin: 20rpx 0;
  color: #999;
  font-size:12pt
}

.bookinfo_list_Ulimg  image{
    width: 100%;
    height: 100%;
}

.bookinfo_list_Ulimg  .span {
    display: block;
    width: 40rpx;
    height: 40rpx;
    background-color: #ff6a00;
    line-height: 40rpx;
    color: #fff;
    font-size: 40rpx;
    text-align: center;
    border-radius: 20rpx;
    position: absolute;
    top: -20rpx;
    right: -20rpx;
}

.bookinfo_list_Ulimg .li {
  width:150rpx; height:150rpx; position: relative;
  margin-right: 20rpx;
 
}

.bookinfo_list_Ulimg {
  padding-top: 20rpx;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.z-Package-hrader .z-Package-icon {
    width: 0.3626rem;
    height: 0.7466rem;
    display: block;
    position: absolute;
    left: 0.64rem;
    top: 0;
}

.z-Package-icon image{
  width: 100%;
  height: 100%;
}

.ul_li .img-item {
  margin-left: 30rpx;
}

.ul_li .img-item:first-child {
  margin-left: 0rpx;
}

</style>